package customer

import (
	"counter-help/admin/server/global"
	"counter-help/admin/server/model/customer"
	customerReq "counter-help/admin/server/model/customer/request"
	customerRes "counter-help/admin/server/model/customer/response"
	"counter-help/admin/server/utils"
	"errors"
	"fmt"
	"github.com/gofrs/uuid/v5"
	"gorm.io/gorm"
	"time"
)

type CusUserService struct{}

// Register 用户注册
func (userService *CusUserService) Register(u customer.CusUser) (userInter customer.CusUser, err error) {
	var user customer.CusUser
	if !errors.Is(global.GVA_DB.Where("phone = ?", u.Phone).First(&user).Error, gorm.ErrRecordNotFound) { // 判断用户名是否注册
		return userInter, errors.New("手机已注册")
	}
	// 否则 附加uuid 密码hash加密 注册
	u.Password = utils.BcryptHash(u.Password)
	u.UUID = uuid.Must(uuid.NewV4())
	err = global.GVA_DB.Create(&u).Error
	return u, err
}

// Login 用户登录
func (userService *CusUserService) Login(u *customer.CusUser) (userInter *customer.CusUser, err error) {
	if nil == global.GVA_DB {
		return nil, fmt.Errorf("db not init")
	}

	var user customer.CusUser
	err = global.GVA_DB.Where("username = ?", u.Username).First(&user).Error
	if err == nil {
		if ok := utils.BcryptCheck(u.Password, user.Password); !ok {
			return nil, errors.New("密码错误")
		}
	}
	return &user, err
}

// UpdateUserInfo 更新用户的个人信息
func (s *CusUserService) UpdateUserInfo(userID uint, req customerReq.UpdateUserInfoRequest) error {
	db := global.GVA_DB.Model(&customer.CusUser{}).Where("id = ?", userID)

	// 更新指定的字段
	updateData := map[string]interface{}{}
	if req.Birth != nil {
		birthTime := time.Unix(*req.Birth, 0) // 将 Unix 时间戳转换为 time.Time
		updateData["birth"] = &birthTime      // 使用指针类型
	}
	if req.Unit != "" {
		updateData["unit"] = req.Unit
	}
	if req.Address != "" {
		updateData["address"] = req.Address
	}
	if req.Nickname != "" {
		updateData["nickname"] = req.Nickname
	}
	if req.Research != "" {
		updateData["research"] = req.Research
	}

	// 执行更新操作
	if err := db.Updates(updateData).Error; err != nil {
		return err
	}

	return nil
}

func (s *CusUserService) GetUserInfo(userID uint) (*customerRes.UserInfoResponse, error) {
	var user customer.CusUser
	err := global.GVA_DB.Where("id = ?", userID).First(&user).Error
	if err != nil {
		global.GVA_LOG.Error("GET UserInfo Error" + err.Error())
		return nil, err
	}

	// 构建响应数据
	responseData := customerRes.UserInfoResponse{
		Nickname: user.Nickname,
		Birth:    user.Birth, // 时间戳
		Unit:     user.Unit,
		Research: user.Research,
		Address:  user.Address,
	}
	return &responseData, nil
}
